package cmms.support;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import sun.org.mozilla.javascript.internal.NativeJavaObject;
import sun.org.mozilla.javascript.internal.NativeObject;
import sun.org.mozilla.javascript.internal.UniqueTag;
import fab.util.S_CST;
import fab.util.StringUtil;

/**
 * @author eltnam
 * @date Apr 28, 2014 3:03:42 PM
 * @description 
 */
public class ScriptService {
	
	public static final int SCRIPT_SUCCESS = 0;
	public static final String RETURN_MSG = "rmsg";
	public static final String RETURN_CODE = "rc";
	
	private ScriptEngineManager engineManager = new ScriptEngineManager();
	private ScriptEngine  engine = engineManager.getEngineByName("javascript");
	
	public Map<String, Object> executeScript(String script, List<String> dstKeys, Map<String, Object> srcKeyValues) throws ScriptException {
		
		if (StringUtil.notNULL(script)) {
			// 设置默认返回代码(默认为0代表成功)
			engine.put(RETURN_CODE, SCRIPT_SUCCESS);
			// 设置默认返回信息
			engine.put(RETURN_MSG, S_CST.BLANK_STRING);
			//TODO handler
		}
		// 将原数据变量带入脚本
		for(Entry<String, Object> entry : srcKeyValues.entrySet()) {
			engine.put(entry.getKey(), entry.getValue());
		}
		//执行脚本
		engine.eval(script);
		//返回值
		Map<String, Object> result = new HashMap<String, Object>(dstKeys.size());
		for (String key : dstKeys) {
			unwrapScriptObject(result, key, engine.get(key));
		}
		// 返回js处理结果
		return result;
	}

	//处理js包装过的数据
	private void unwrapScriptObject(Map<String, Object> result, String key, Object value) {
		if (value instanceof NativeJavaObject) {
			result.put(key, ((NativeJavaObject) value).unwrap());
		} else if (value instanceof NativeObject) {
			Object[] subObjs = ((NativeJavaObject) value).getIds();
			if(subObjs.length > 0) {
				Map<String, Object> subResult = new HashMap<String, Object>(subObjs.length);
				for (int i = 0; i < subObjs.length; i++) {
					unwrapScriptObject(subResult, subObjs[i].toString(), subObjs[i]);
				}
				result.put(key, subResult);
			}
		} else if(value instanceof UniqueTag){
			System.out.println(key + " is a NOT FOUND NULL_VALUE");
		} else {
			result.put(key, value);
		}
	}

}
